package com.legna.mhxy.support.utils;

import org.apache.poi.ss.usermodel.Cell;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author jinchaofan
 * @date 2018/9/19 11:11
 * @company kiisoo
 * @details
 */
public class ExcelUtils {

    /**
     * 是否是2007的excel，返回true是2007
     * @param filePath 文件路径
     * @return boolean
     */
    public static boolean isExcel2007(String filePath) {
        return filePath.matches("^.+\\.(?i)(xlsx)$");
    }

    /**
     * 读取cell单元格的值，如果为日期格式，进行转换
     * @author  jinchaofan
     * @param cell 名字
     * @return String
     */
    @SuppressWarnings("deprecation")
    public static String getCellValue(Cell cell) {
        if (cell == null) {
            return "";
        }
        if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
            return cell.getStringCellValue();
        } else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
            return String.valueOf(cell.getBooleanCellValue());
        } else if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
            return cell.getCellFormula();
        } else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
            short format = cell.getCellStyle().getDataFormat();

            SimpleDateFormat sdf;
            if (format == 14 || format == 31 || format == 57 || format == 58
                    || (176 <= format && format <= 178) || (182 <= format && format <= 196)
                    || (210 <= format && format <= 213) || (208 == format)) {
                // 日期
                sdf = new SimpleDateFormat("yyyy-MM-dd");
            } else if (format == 20 || format == 32 || format == 183 || (200 <= format && format <= 209)) {
                // 时间
                sdf = new SimpleDateFormat("HH:mm");
            } else if(format == 0) {
            	DecimalFormat df = new DecimalFormat("#");
            	return df.format(cell.getNumericCellValue());
            } else {
                // 不是日期格式
                return String.valueOf(cell.getNumericCellValue());
            }
            double value = cell.getNumericCellValue();
            Date date = org.apache.poi.ss.usermodel.DateUtil.getJavaDate(value);
            if (date == null || "".equals(date)) {
                return "";
            }
            String result;
            try {
                result = sdf.format(date);
            } catch (Exception e) {
                e.printStackTrace();
                return "";
            }
            return result;
        }
        return "";
    }


}
